package com.mali.malibackenduser.controller;


import com.mali.backendcommon.common.Result;
import com.mali.backendcommon.constant.MessageConstant;

import com.mali.backendcommon.constant.RedisConstant;
import com.mali.backendcommon.properties.JwtProperties;
import com.mali.backendcommon.util.RedisUtil;
import com.mali.malibackendmodel.dto.SendEmailDTO;
import com.mali.malibackendmodel.dto.UserLoginDTO;
import com.mali.malibackendmodel.dto.UserRegisterDTO;
import com.mali.malibackendmodel.dto.UserResetDTO;
import com.mali.malibackendmodel.pojo.User;
import com.mali.malibackendmodel.vo.UserLoginVO;
import com.mali.malibackendmodel.vo.UserVO;
import com.mali.backendcommon.rpc.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/user")
@Slf4j
@CrossOrigin(origins = "*", allowedHeaders = "*")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private JwtProperties jwtProperties;
    @PostMapping("/code")
    public Result sendCode (@RequestBody SendEmailDTO sendEmailDTO)
    {
        log.info("验证码发送：{}", sendEmailDTO);
        String account = sendEmailDTO.getAccount();
        String email = sendEmailDTO.getEmail();
        if (sendEmailDTO == null) {
            throw new RuntimeException(MessageConstant.PARAMETER_IS_NULL);
        }
        if (StringUtils.isAnyBlank(account, email)) {
            throw new RuntimeException(MessageConstant.PARAMETER_IS_NULL);
        }
        userService.sendCode(account,email);
        return Result.success();
    }

    @PostMapping("/register")
    public Result userRegister(@RequestBody UserRegisterDTO userRegisterDTO )
    {
        log.info("用户注册：{}", userRegisterDTO);
        //参数检验
        if (userRegisterDTO == null) {
            throw new RuntimeException(MessageConstant.PARAMETER_IS_NULL);
        }
        String account = userRegisterDTO.getAccount();
        String userName = userRegisterDTO.getUserName();
        String password = userRegisterDTO.getPassword();
        String email = userRegisterDTO.getEmail();
        String securityCode = userRegisterDTO.getSecurityCode();

        if (StringUtils.isAnyBlank(userName, account.toString(), password,email,securityCode)) {
            throw new RuntimeException(MessageConstant.PARAMETER_IS_NULL);
        }
        //注册用户
        userService.register(account,userName,password,email,securityCode);
        return Result.success();
    }
    @GetMapping("/hello/{id}")
    public Result hello(@PathVariable String id )
    {
        throw new RuntimeException(MessageConstant.PARAMETER_IS_NULL);
    }


    @PostMapping ("/login")
    public Result<UserLoginVO> userLogin(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("员工登录：{}", userLoginDTO);
        if (userLoginDTO == null) {
            throw new RuntimeException(MessageConstant.PARAMETER_IS_NULL);
        }
        String account = userLoginDTO.getAccount();
        String password = userLoginDTO.getPassword();
        if (StringUtils.isAnyBlank(account, password)) {
            throw new RuntimeException(MessageConstant.PARAMETER_IS_NULL);
        }
        UserLoginVO userLoginVO=userService.login(account,password);
        return Result.success(userLoginVO);
    }
    @DeleteMapping("/logout")
    public Result userLogout(HttpServletRequest request)
    {
        log.info("用户退出登录");
        String token = request.getHeader(jwtProperties.getUserTokenName());
        userService.logout(token);
        return Result.success();

    }
    @PutMapping("/reset")
    public Result UserPasswordReset(@RequestBody UserResetDTO userResetDTO) {
        log.info("用户找回密码：{}", userResetDTO);
        //1.数据检验
        if (userResetDTO == null) {
            throw new RuntimeException(MessageConstant.PARAMETER_IS_NULL);
        }
        String account = userResetDTO.getAccount();
        String securityCode = userResetDTO.getSecurityCode();
        String newPassword = userResetDTO.getNewPassword();

        if (StringUtils.isAnyBlank(account, securityCode,newPassword)) {
            throw new RuntimeException(MessageConstant.PARAMETER_IS_NULL);
        }
        //更新数据 并在service删除缓存
        userService.resetPassword(account,securityCode,newPassword);
        return Result.success();
    }
    @GetMapping("/get/{id}")
    public Result<UserVO> getUserById(@PathVariable Long id) {
        log.info("通过用户ID查询用户：{}", id);
        //1.对ID进行非空校验
        if (Objects.isNull(id) || id <= 0) {
            throw new RuntimeException(MessageConstant.PARAMETER_IS_NULL);
        }
        UserVO userVO=new UserVO();
        //2.从缓存获取
        User user = (User) redisUtil.get(RedisConstant.userId + id);
        //redis存在数据 返回数据
        if(user!=null){
            BeanUtils.copyProperties(user,userVO);
            return Result.success(userVO);
        }
        //3.数据库获取 并在service将数据存入缓存
        userVO = userService.getByUserId(id);
        return Result.success(userVO);
    }
    @GetMapping("/list/{userName}")
    public Result<List<UserVO>> getListByUserName(@PathVariable String userName ) {
        log.info("通过用户名模糊查询：{}", userName);
        if (StringUtils.isEmpty(userName)) {
            throw new RuntimeException(MessageConstant.PARAMETER_IS_NULL);
        }
        List<UserVO> list = userService.getListByUserName(userName);

        return Result.success(list);
    }



}
